﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ArticleWeb.Common
{
    public class IPHelper
    {
        public static string getIp()
        {
            string ret = null;
            try
            {
                if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                    ret = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(new char[] { ',' })[0];
                else
                    ret = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                if (IsIP(ret))
                    return ret;
            }
            catch { }
            return "";
        }
        private static bool IsIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
    }
}